package com.tul.exercise.base.thread.synchronize;

/**
 * 双重检查的问题示例
 * @author tuliang
 */
public class DoubleCheckProblem {


}

class LazyInitDemo{

    // 多线程情况情况下会导致得到未初始化的对象
    private static TransactionService service = null;

    // 解决方法之一就是使用volatile修饰初始化对象
    private static volatile TransactionService service2 = null;
    /**
     * TransactionService 初始化，使用双重检查机制
     * @return TransactionService
     */
    public static TransactionService getTransactionService() {
        if (service == null) {
            synchronized (LazyInitDemo.class) {
                if (service == null) {
                    service = new TransactionService();

                    // service2变量是volatile，读的时候不会出现问题
                    service2 = new TransactionService();
                }
            }
        }
        return service;
    }
}

/**
 * 业务类
 */
class TransactionService {

}
